import React, { useState, useEffect, useRef } from 'react';
export const debounce = function (func, wait = 1000) {
    let startTime = Date.now();
    let timer;

    return (...args) => {
        if (Date.now() - startTime < wait && timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func(...args);
        }, wait);
        startTime = Date.now();
    };
};

export const throttle = function (func, delay = 1000) {
    let lastTime = 0;
    return (...args) => {
        const nowTime = new Date().getTime();
        if (nowTime - lastTime > delay) {
            func.apply(this, args);
            lastTime = nowTime;
        }
    };
};

export const useInterval = (callback, delay) => {
    const savedCallback = useRef(callback);

    // Remember the latest callback.
    useEffect(() => {
        savedCallback.current = callback;
    }, [callback]);

    // Set up the interval.
    useEffect(() => {
        function tick() {
            savedCallback.current();
        }
        if (delay !== null) {
            let id = setInterval(tick, delay);
            return () => clearInterval(id);
        }
    }, [delay]);
};

export const converterTree = (
    treeData,
    converterFunc = (e) => e,
    childName = 'children',
    sortFunc = (a, b) => 0
) => {
    if (!treeData) return null;
    const treeDataList = [...(treeData || [])];
    return treeDataList
        .map((dataItem) => {
            const converItem = converterFunc(dataItem);
            if (converItem) {
                converItem[childName] = converterTree(
                    dataItem?.[childName],
                    converterFunc,
                    childName,
                    sortFunc
                );
            }
            return converItem;
        })
        .sort(sortFunc);
};

export const listToTree = (list, idKey, parentKey) => {
    let map = {}, tree = [], i;

    // 初始化每个节点，并建立一个map，以id为key，节点引用为值。
    for (i = 0; i < list.length; i++) {
        map[list[i][idKey]] = list[i];
        list[i].children = []; // 初始化children数组
    }

    for (i = 0; i < list.length; i++) {
        let node = list[i];
        if (node[parentKey]) {
            // 如果存在父节点
            if (map[node[parentKey]]) {
                // 如果父节点在map中
                map[node[parentKey]].children.push(node);
            } else {
                // 没有找到父节点的情况，可能需要根据实际情况处理，这里直接添加到树的根部
                tree.push(node);
            }
        } else {
            // 没有父节点，是树的根
            tree.push(node);
        }
    }

    return tree;
}

export const tileTree = (treeData, childName = 'children') => {
    return treeData.reduce((result, node) => {
        result.push(node);
        if (node[childName]) {
            result.push(...tileTree(node[childName], childName));
        }
        return result;
    }, []);
};


export const filterTree = (treeArray, filterFn, childrenKey = 'children') => {
    return treeArray.map(tree => filterTreeNode(tree, filterFn, childrenKey)).filter(tree => tree !== null);
}

function filterTreeNode(node, filterFn, childrenKey) {
    // 如果节点有子节点，递归过滤子节点
    if (node[childrenKey] && node[childrenKey].length > 0) {
        node[childrenKey] = node[childrenKey].map(childNode => filterTreeNode(childNode, filterFn, childrenKey)).filter(child => child !== null);
    }
    
    // 如果节点通过筛选函数，或者它有子节点（经过过滤后可能为空），则保留节点
    if (filterFn(node) || (node[childrenKey] && node[childrenKey].length > 0)) {
        return node;
    }
    
    // 否则，移除节点
    return null;
}


export const triggerSingleImageUpload = (onFileSelect) => {
    // 创建一个隐藏的input元素
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*'; // 只接受图片文件
    fileInput.style.display = 'none'; // 隐藏input元素

    // 监听文件选择事件
    fileInput.addEventListener('change', (event) => {
        // 从DOM中移除file input元素
        document.body.removeChild(fileInput);
        // 调用回调函数处理文件选择事件
        onFileSelect(event);
    });

    // 添加到body中以便能够触发点击事件
    document.body.appendChild(fileInput);

    // 模拟点击事件
    fileInput.click();
}

export const formatAmount = (amount) => {
    if (amount > 10000) {
        return `${parseFloat(Math.abs(amount) / 10000).toFixed(2)}万`;
    } else if (amount > 1000) {
        return `${parseFloat(Math.abs(amount) / 1000).toFixed(2)}千`;
    }
    return parseFloat(Math.abs(amount)).toFixed(2);
}